package com.allianz.webapps.secondController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.allianz.webapps.common.CustomerContextHolder;
import com.allianz.webapps.https.interfaces.type001.pojo.User;
import com.allianz.webapps.service.OrdersTraceService;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping(value = "myPolicy")
public class OrdersTraceController {
	
	@Autowired
	private OrdersTraceService ordersTraceService;
	
	@Autowired
	private ObjectMapper objectMapper;

	/**
	 * 我的保单,新单追踪按条件查询保单
	 * @param jsonParam
	 * @param session
	 * @return
	 * @throws Exception
	 * URL:/pad_marketing/myPolicy/getAllTrace.action
	 */
	@RequestMapping(value = "getAllTrace")
	@ResponseBody
	public List<Map<String, Object>> getAllTrace(@RequestParam(value = "jsonParam") String jsonParam, HttpSession session) throws Exception {
		CustomerContextHolder.setCustomerType(CustomerContextHolder.DATA_SOURCE_ALLIANZ);
		Map<String, Object> map = objectMapper.readValue(jsonParam, Map.class);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		GregorianCalendar gc = new GregorianCalendar();
		if(map.get("issueDateFrom").toString() != null && !"".equals(map.get("issueDateFrom").toString().trim())
		&& map.get("issueDateTo").toString() != null && !"".equals(map.get("issueDateTo").toString().trim())) {
			Date issueDateFrom = sdf.parse(map.get("issueDateFrom").toString());
			Date issueDateTo = sdf.parse(map.get("issueDateTo").toString());
			if(issueDateFrom.getTime() > issueDateTo.getTime()) {
				throw new Exception("承保日期的起始日期不能大于截止日期");
			} else {
				gc.setTime(issueDateFrom);
				gc.add(5, 90);
				issueDateFrom = gc.getTime();
				if(issueDateFrom.getTime() < issueDateTo.getTime()) {
					throw new Exception("承保日期查询区间不能超过90天");
				}
			}
		}
		User user = (User) session.getAttribute("username");
		map.put("agentId", Long.parseLong(user.getAgentId()));
		try {
			return ordersTraceService.getAllTrace(map);
		} catch (Exception e) {
			throw new Exception("查询失败,请重试");
		}
	}
}
